package com.yichuang.security.javajwt.main.config;

import com.yichuang.security.common.ResultData;
import com.yichuang.security.common.ServerStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;


/**
 * <p> OAuth标准异常转换器 将 OAuth2Exception 转换成 自定义异常
 * 1.异常包含：invalid_request、invalid_token、invalid_grant、unauthorized_client、invalid_scope、server_error、temporarily_unavailable
 * 2.自定义方式
 * public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
 *     // 设置授权服务器异常转换器
 *     endpoints.exceptionTranslator(new Auth2ResponseExceptionTranslator());
 * }
 * </p>
 *
 * @author tuonioooo
 * @site https://miliqkdoc.motopa.cn/
 * @date 2018/8/22 14:20
 */
@Slf4j
@Component
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        log.info("OAuth2Exception=【{}】", e.getMessage());
        //设置编码
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.valueOf("application/json;charset=utf-8"));
        if (e instanceof InsufficientAuthenticationException) {
            return new ResponseEntity(ResultData.fail(ServerStatusEnum.INVALID_TOKEN.getCode(), e.getMessage()), requestHeaders, HttpStatus.OK);
        }
        if ( e instanceof InvalidClientException){
            return new ResponseEntity(ResultData.fail(ServerStatusEnum.UNAUTHORIZED.getCode(), e.getMessage()), requestHeaders, HttpStatus.OK);
        }
        return new ResponseEntity(ResultData.fail(ServerStatusEnum.ERROR_REQUEST.getCode(), e.getMessage()), requestHeaders, HttpStatus.OK);
    }
}
